'use strict';

const Controller = require('egg').Controller;
const ulid = require('../public/ulid');
const sequelize = require('sequelize');
const { getCookieValue } = require('../public/processCookies');
const { valueFromASTUntyped } = require('graphql');
/**
 * @controller OltProfileController 注释必写，swagger-doc是根据这段注释来生成接口的 ）。
 */
class OltProfileController extends Controller {
    /**
     * @summary OLTProfile列表分页。
     * @description OLTProfile列表分页。
     * @router get /oltProfile
     * @request query integer limit
     * @request query integer page
     * @request query String OltId
     * @request query String Name
     * @request query String type
     */
    async list() {
        try {
            let {
                ctx
            } = this;
            const { id: tid } = getCookieValue(ctx.cookies, 'token', 'tenant');
            let where = {tid};
            let {OltId,type,Name,page,limit} = ctx.query;
            if(OltId!=='Any'){
                where.oltId = OltId;
            }
            if(type&&type!=='Any'){
                where.type = type;
            }
            if(Name){
                where.name=new RegExp(Name,'i');
            }
            let count = await this.ctx.model.OltProfile.find(where).count();
            let data = await this.ctx.model.OltProfile.find(where).skip(parseInt((page - 1) * limit))
            .limit(parseInt(limit));
    
            ctx.body = {
                msg: '',
                status: 200,
                count: count,
                data: data
            }
        } catch (error) {
            console.log(error)
            this.ctx.body = {
                msg:'error',
                status:500
            }
        }
        
    }
    /**
     * @summary oltProfileListAll
     * @description oltProfile 不分页
     * @router get /oltProfileListAll
     * @request query integer limit
     * @request query integer page
     * @request query String OltId
     * @request query String Name
     * @request query String type
     */
    async listAll(){
        try {
            let {
                ctx
            } = this;
            const { id: tid } = getCookieValue(ctx.cookies, 'token', 'tenant');
            let where = {tid};
            let {OltId,type,Name,page,limit} = ctx.query;
            if(OltId!=='Any'){
                where.oltId = OltId;
            }
            if(type&&type!=='Any'){
                where.type = type;
            }
            if(Name){
                where.name=new RegExp(Name,'i');
            }
            let count = await this.ctx.model.OltProfile.find(where).count();
            let data = await this.ctx.model.OltProfile.find(where)
    
            ctx.body = {
                msg: '',
                status: 200,
                count: count,
                data: data
            }
        } catch (error) {
            console.log(error)
            this.ctx.body = {
                msg:'error',
                status:500
            }
        }
    }
    /**
     * @summary 刷新vlan-profile\ip-profile\sip-profile
     * @description 刷新vlan-profile\ip-profile\sip-profile 这三个是一起刷的
     * @router get /oltProfileRefresh
     * @request query String OltId
     */
    async refresh() {
        let { ctx } = this;
        const params = ctx.query;
        const { id: tid } = getCookieValue(ctx.cookies, 'token', 'tenant');
        params.tid = tid;
        if(params.OltId==='Any'){
            const oltResults = await this.ctx.model.Olt.find({tid:params.tid})
            for(var i=0;i<oltResults.length;i++){
                try {
                    let oltResult = oltResults[i];
                    let profiles = await this.ctx.service.wanProfile.refreshOltProfile(oltResult);
                    //插入数据库
                    if(profiles){

                        await this.ctx.service.wanProfile.insertOltProfiles(profiles,oltResult._id,tid);
                    }
                } catch (error) {
                    console.log(error)
                }                
            }
        }else{
            try {
                let oltResult = await this.ctx.service.common.getOltInfo(params.OltId);
                let profiles = await this.ctx.service.wanProfile.refreshOltProfile(oltResult);
                //插入数据库
                await this.ctx.service.wanProfile.insertOltProfiles(profiles,params.OltId,tid);
            } catch (error) {
                console.log(error)
            }
        }
        ctx.body = {
            msg: 'ok',
            status: 200,
        }

    }
    
    async create() {
        /**
         * @summary oltProfile添加。
         * @description oltProfile添加。
         * @router post /oltProfile
         * @request body oltProfile value 传入参数
         */
        let {
            ctx
        } = this;
        try {
            let {type,name,context,oltId} = ctx.request.body;
            let oltProfile = JSON.parse(context);
            oltProfile.type = type;
            oltProfile.name = name;
            //校验名字是否重复
            let old = await ctx.model.OltProfile.findOne({name:name});
            if(old){
                ctx.body = {
                    msg:'profile name repeat',
                    status:400
                }
                return;
            }
            let flag = this.validOltProfile(oltProfile);
            if(!flag){
                ctx.body = {
                    msg:'context property invalided',
                    status:400
                }
                return;
            }
            const { id: tid } = getCookieValue(ctx.cookies, 'token', 'tenant');
            let oltInfomation = await ctx.service.common.getOltInfo(oltId);
            //step1 向发送命令 创建oltProfile 
            let result = await ctx.service.wanProfile.createOltProfile(oltInfomation,oltProfile)
            //step2 插入数据库
            if(result){
                oltProfile._id=ulid.ulid();
                
                oltProfile.tid = tid;
                oltProfile.oltId = oltInfomation._id;
                let obj = {
                    _id:ulid.ulid(),
                    name:oltProfile.profileName,
                    type:oltProfile.type,
                    context:JSON.stringify(oltProfile),
                    tid:tid,
                    oltId:oltInfomation._id
                }
                await ctx.model.OltProfile.create(obj);
            }
            
            ctx.body = {
                msg: 'ok',
                status: 200,
            }
        } catch (error) {
            ctx.body = {
                msg: 'error',
                status: 500,
            }
        }
        
    }
    validOltProfile(oltProfile){
        let flag = true;
        if(oltProfile.type){
            switch(oltProfile.type){
                case "vlan-profile":
                    let vlanAttribute = ["profileName","tagMode","cVlan","cVlanPriority","sVlan"]
                    for(let i =0;i<vlanAttribute.length;i++){
                        let key = vlanAttribute[i]
                        if(!oltProfile.hasOwnProperty(key)){
                            flag=false;
                            break;
                        }
                    }
                    break;
                case "ip-profile":
                    let ipAttribute = ["profileName","gateway"]
                    for(let i =0;i<ipAttribute.length;i++){
                        let key = ipAttribute[i]
                        if(!oltProfile.hasOwnProperty(key)){
                            flag=false;
                            break;
                        }
                    }
                    break;
                case "sip-profile":
                    let sipAttribute = ["profileName","proxyServer","registrar"]
                    for(let i =0;i<sipAttribute.length;i++){
                        let key = sipAttribute[i]
                        if(!oltProfile.hasOwnProperty(key)){
                            flag=false;
                            break;
                        }
                    }
                    break;
            }
        }
        return flag;
    }
    async detele() {
        /**
         * @summary OLTProfile删除。
         * @description OLTProfile删除。
         * @router delete /oltProfile
         * @request body oltProfile value 传入参数
         */
        let {
            ctx
        } = this;
        try {
            let {id} = ctx.request.body;
            let oltProfileResult = await ctx.model.OltProfile.findOne({_id:id});
            if(!oltProfileResult){
                ctx.body = {
                    msg: 'data not found ',
                    status: 400,
                }
                return;
            }
            let oltInformation = await ctx.service.common.getOltInfo(oltProfileResult.oltId);
            
            let oltProfile = JSON.parse(oltProfileResult.context);
            oltProfile.type = oltProfileResult.type;
            //step1 发送命令删除profile
            let res = await ctx.service.wanProfile.deleteOltProfile(oltInformation,oltProfile);
            //step2 删除数据
            if(res){
                let a = await ctx.model.OltProfile.remove({
                    _id:id
                })
                console.log(a)
                ctx.body = {
                    msg: 'ok',
                    status: 200,
                }
            }else{
                ctx.body = {
                    msg: 'delete profile false',
                    status: 400,
                }
            }
            
        } catch (error) {
            ctx.body = {
                msg: 'error',
                status: 500,
            }
        }
    }

}

module.exports = OltProfileController;